import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";

axios.defaults.baseURL = "http://localhost:3001";

// 请求拦截器
axios.interceptors.request.use((config) => {
  // 从 localStorage 获取 token
  const token = localStorage.getItem("token");
  // 如果 token 存在，则添加到请求头
  if (token) {
    config.headers["Authorization"] = `${token}`; // 根据后端要求设置格式
  }
  return config;
});

// 响应拦截器
axios.interceptors.response.use((response) => {
  // 未登录时携带url跳转到登录页
  const { code } = response.data;
  if (code === 1001) {
    window.location.href = `http://localhost:8080/login?redirect_url=${window.location.href}`
  }
  else return response.data;
});

Vue.use(VueAxios, axios);
